const Router = require('koa-router');
const router = new Router();
const {db, QueryTypes} = require("../../models/db");
const tools = require("../../tools/tool");

router.post('/zq/toClosed', async ctx => {
    try {
        let user = ctx.user
        let body = ctx.request.body
        let tenantId = user.tenantId;
        let ym = body.ym;
        let lastZq = await db.query(`select top 1 * from zq where tenantId=${tenantId} order by id desc `,{type: QueryTypes.SELECT,plain: true})
        if(!lastZq) return ctx.err('还没有开始账套')
        if(tools.dayjs(ym).isAfter(tools.getDay())) {
            return ctx.err('日期不能大于今天')
        }
        if(tools.dayjs(ym).isAfter(lastZq.ym)) {
            // 检测是否在此日期前还有未审核的票据
            let endDate = tools.getDay(ym, -1)
            let beginDate = lastZq.ym
            let c = await db.query(`select count(*) total from invoice where tenantId=${tenantId} and billState='draft' and billDate between '${beginDate}' and '${endDate}' `,{type: QueryTypes.SELECT, plain: true})
            if(c) {
                if(c.total > 0) {
                    return ctx.err(`在结账日期 ${ym} 前还有 ${c.total} 条票据没有审核`)
                }
            }
            let zq = {
                tenantId,
                ym,
                ctime: tools.getTime(),
                cby: user.id
            }
            await db.models['zq'].create(zq)
            return ctx.suc('已结账')
        }
        else {
            return ctx.err('日期只能大于上次结账日期')
        }
    } catch (e) {
        return ctx.err('无返回数据')
    }
})
const setProfit = async (ctx) => {
    let body = ctx.request.body
    let ym = body.ym
    let user = ctx.user
    let tenantId = user.tenantId;
    let sqls = `exec card_jz @tenantId=${tenantId},@ym='${ym}'`
    await db.query(sqls, {type: QueryTypes.UPDATE})
    let lists = await db.models['profit'].findAll({
        where: {
            tenantId
        }
    })
    let yb = ym.substring(0, 4) + "-01-01"
    let mb = ym + "-01"
    let me = tools.getDayStart(mb,'end')
    if (lists.length == 0) {
        return ctx.err('利润表未初始化')
    }
    // let cardsql = """SELECT  sum(iif(c.direct=N'借', price1-price2, price2-price1)) amount from card
    // a INNER JOIN card_info b on a.id=b.cardId
    // inner join category c on b.subjectId=c.id and a.tenantId=#{tenantId} and a.billState='accounted' """
    // for (profit in lists) {
    //     profit.ym = ym
    //     if (not_blank(profit.subjectCode) && not_null(profit.direct)) {
    //         let scode = profit.subjectCode
    //         let listM = []
    //         let listY = []
    //         if (scode.equals("6711")) {
    //             listY = db.select(cardsql + " and a.billDate between #{yb} and #{me} and (subjectCode like '${scode}%' or subjectCode like '6710%'  )  ")
    //             listM = db.select(cardsql + " and a.billDate between #{mb} and #{me} and (subjectCode like '${scode}%' or subjectCode like '6710%'  ) ")
    //         } else {
    //             listY = db.select(cardsql + " and a.billDate between #{yb} and #{me} and subjectCode like '${scode}%' ")
    //             listM = db.select(cardsql + " and a.billDate between #{mb} and #{me} and subjectCode like '${scode}%'")
    //         }
    //         profit.amountM = listM.size() > 0 ? listM[0].amount : 0
    //         profit.amountY = listY.size() > 0 ? listY[0].amount : 0
    //     }
    // }
    // let a0m = not_null(lists[0].amountM) ? lists[0].amountM.asDecimal() : '0'.asDecimal()
    // let a1m = not_null(lists[1].amountM) ? lists[1].amountM.asDecimal() : '0'.asDecimal()
    // let a2m = not_null(lists[2].amountM) ? lists[2].amountM.asDecimal() : '0'.asDecimal()
    // let a3m = not_null(lists[3].amountM) ? lists[3].amountM.asDecimal() : '0'.asDecimal()
    // let a4m = not_null(lists[4].amountM) ? lists[4].amountM.asDecimal() : '0'.asDecimal()
    // let a5m = not_null(lists[5].amountM) ? lists[5].amountM.asDecimal() : '0'.asDecimal()
    // let a6m = not_null(lists[6].amountM) ? lists[6].amountM.asDecimal() : '0'.asDecimal()
    // let a7m = not_null(lists[7].amountM) ? lists[7].amountM.asDecimal() : '0'.asDecimal()
    // let a8m = not_null(lists[8].amountM) ? lists[8].amountM.asDecimal() : '0'.asDecimal()
    // let a9m = not_null(lists[9].amountM) ? lists[9].amountM.asDecimal() : '0'.asDecimal()
    // let a10m = not_null(lists[10].amountM) ? lists[10].amountM.asDecimal() : '0'.asDecimal()
    // let a11m = not_null(lists[11].amountM) ? lists[11].amountM.asDecimal() : '0'.asDecimal()
    // let a12m = not_null(lists[12].amountM) ? lists[12].amountM.asDecimal() : '0'.asDecimal()
    // let a13m = not_null(lists[13].amountM) ? lists[13].amountM.asDecimal() : '0'.asDecimal()
    // //
    // let a0y = not_null(lists[0].amountY) ? lists[0].amountY.asDecimal() : '0'.asDecimal()
    // let a1y = not_null(lists[1].amountY) ? lists[1].amountY.asDecimal() : '0'.asDecimal()
    // let a2y = not_null(lists[2].amountY) ? lists[2].amountY.asDecimal() : '0'.asDecimal()
    // let a3y = not_null(lists[3].amountY) ? lists[3].amountY.asDecimal() : '0'.asDecimal()
    // let a4y = not_null(lists[4].amountY) ? lists[4].amountY.asDecimal() : '0'.asDecimal()
    // let a5y = not_null(lists[5].amountY) ? lists[5].amountY.asDecimal() : '0'.asDecimal()
    // let a6y = not_null(lists[6].amountY) ? lists[6].amountY.asDecimal() : '0'.asDecimal()
    // let a7y = not_null(lists[7].amountY) ? lists[7].amountY.asDecimal() : '0'.asDecimal()
    // let a8y = not_null(lists[8].amountY) ? lists[8].amountY.asDecimal() : '0'.asDecimal()
    // let a9y = not_null(lists[9].amountY) ? lists[9].amountY.asDecimal() : '0'.asDecimal()
    // let a10y = not_null(lists[10].amountY) ? lists[10].amountY.asDecimal() : '0'.asDecimal()
    // let a11y = not_null(lists[11].amountY) ? lists[11].amountY.asDecimal() : '0'.asDecimal()
    // let a12y = not_null(lists[12].amountY) ? lists[12].amountY.asDecimal() : '0'.asDecimal()
    // let a13y = not_null(lists[13].amountY) ? lists[13].amountY.asDecimal() : '0'.asDecimal()
    // a0m = a1m.asDecimal().add(a2m)
    // a0y = a1y.asDecimal().add(a2y)
    // lists[0].amountM = a0m
    // lists[0].amountY = a0y
    // // 营业利润
    // a8m = a0m.asDecimal().subtract(a3m).subtract(a4m).subtract(a5m).subtract(a6m).subtract(a7m)
    // a8y = a0y.asDecimal().subtract(a3y).subtract(a4y).subtract(a5y).subtract(a6y).subtract(a7y)
    // lists[8].amountM = a8m
    // lists[8].amountY = a8y
    // // 利润总额
    // a11m = a8m.add(a9m).subtract(a10m)
    // a11y = a8y.add(a9y).subtract(a10y)
    // lists[11].amountM = a11m
    // lists[11].amountY = a11y
    // // 净利润
    // lists[13].amountM = a11m.subtract(a12m)
    // lists[13].amountY = a11y.subtract(a12y)
    // // 写入当前利润表
    // db.update("delete from profit_current where tenantId=#{tenantId}")
    // for (it in lists) {
    //     let save = {
    //         tenantId,
    //         code: it.code,
    //         name: it.name,
    //         op: it.op,
    //         amountM: it.amountM ? it.amountM : 0,
    //         amountY: it.amountY ? it.amountY : 0,
    //         amountM3: 0,
    //         isSum: it.isSum,
    //         disabled: it.disabled,
    //         space: it.space,
    //         click: it.click,
    //         isSubject: it.isSubject,
    //         subjectName: it.subjectName,
    //         subjectCode: it.subjectCode,
    //         direct: it.direct,
    //         hasChild: it.hasChild,
    //         ym: it.ym
    //     }
    //     db.table('profit_current').withBlank().primary('id').save(save)
    // }
    // return suc('', lists)
}
module.exports = router;
